<template>
  <div id="Investor_vue">
    <div class="toolbar" @submit.native.prevent>
      <el-form inline @submit.native.prevent>
        <el-form-item>
          <el-input :placeholder="'请输入关键字 ( ' + tableParam.dropdown[tableParam.keycurrent].value + ' )'" v-model="tableParam._keyword" size="mini"></el-input>
        </el-form-item>
        <el-form-item>
          <el-dropdown split-button="" type="primary" @command="updateKeyCurrent" @click="tableParam.keyword = tableParam._keyword; tableParam.pageno = 1; query();" size="mini">
            <i class="el-icon-search" style="margin-right:5px;"></i>查询
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="item in tableParam.dropdown" :command="item.key" :key="item.key + '_dropdown'">{{item.value}}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button disabled type="primary" icon="el-icon-plus" @click="recordFormInit(); recordForm.visible = true; recordForm.flag = true;" size="mini">新增</el-button>
        </el-form-item>
      </el-form>
    </div>
    <sample-table :data="records" :isloading="tableParam.loading" sortcustom @afterSortChange="sortChange" @selectionChange="selectionChange">
      <sample-table-header slot="header">
        <sample-table-header-selection />
        <sample-table-header-column label="机构/公司" prop="ZK_TITLE" sortable />
        <sample-table-header-column label="LOGO" prop="ZK_LOGO" sortable />
        <sample-table-header-column label="是否同步" prop="ZK_ISSYNC" sortable />
        <sample-table-header-column label="收录时间" prop="EB_CREATE_DATETIME" sortable />
        <sample-table-header-column label="最后修改" prop="EB_LASTMODIFY_DATETIME" sortable />
        <sample-table-header-column label="操作" />
      </sample-table-header>
      <sample-table-body slot-scope="scope" :row="scope.row" :index="scope.index" slot="body">
        <sample-table-body-selection />
        <sample-table-body-column prop="ZK_TITLE" />
        <sample-table-body-column>
          <img class="column_logo" :src="scope.row.ZK_LOGO" alt="暂无图片" />
        </sample-table-body-column>
        <sample-table-body-column>
          <span class='tag-warning' v-if="scope.row.ZK_ISSYNC === '0'">未同步</span>
          <span class='tag-success' v-if="scope.row.ZK_ISSYNC === '1'">已同步</span>
        </sample-table-body-column>
        <sample-table-body-column>
          {{$common.ChangeDateFormat_hhmmss(scope.row.EB_CREATE_DATETIME, '-')}}
        </sample-table-body-column>
        <sample-table-body-column>{{$common.ChangeDateFormat_hhmmss(scope.row.EB_LASTMODIFY_DATETIME, '-')}}</sample-table-body-column>
        <sample-table-body-column>
          <i class="el-icon-edit icon-btn-edit" @click="recordFormInit(); getRecord(scope)"></i>
          <i class="el-icon-delete icon-btn-del" @click="delRecord(scope)"></i>
        </sample-table-body-column>
      </sample-table-body>
    </sample-table>
    <el-col :span="24" class="botton_toolbar">
      <el-button type="danger" :disabled="selection.length === 0" icon="el-icon-delete" @click="batchDelete" size="mini">
        批量删除<span v-if="selection.length !== 0"> (共{{selection.length}}条)</span>
      </el-button>
      <el-button type="warning" :disabled="selection.length === 0" icon="el-icon-upload" @click="batchSync" size="mini">
        批量同步<span v-if="selection.length !== 0"> (共{{selection.length}}条)</span>
      </el-button>
      <el-pagination layout="prev, pager, next, jumper, total" :page-size="tableParam.pagesize" :current-page="tableParam.pageno" :total="tableParam.total" @current-change="currentChange" style="float:right;">
      </el-pagination>
    </el-col>
    <el-dialog :title="recordForm.flag ? '新增' : '编辑'" :visible="recordForm.visible" width="80%" :show-close="false">
      <el-form ref="recordForm" class="recordForm" label-width="80px" :model="recordForm.record.ZK_INVESTOR" :rules="recordformRules" @submit.native.prevent>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="名　称" prop="ZK_TITLE">
              <el-input v-model="recordForm.record.ZK_INVESTOR.ZK_TITLE" placeholder="请输入机构名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="LOGO" prop="ZK_LOGO">
              <el-col :span="17">
                <el-input v-model="recordForm.record.ZK_INVESTOR.ZK_LOGO" placeholder="请上传LOGO或填写LOGO路径"></el-input>
              </el-col>
              <el-col :span="7">
                <el-button size="small" type="primary" disabled>点击上传</el-button>
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="简　介">
              <vue-html5-editor :content="recordForm.record.ZK_INVESTOR.ZK_DESC" :height="300" @change="updateContent"></vue-html5-editor>
            </el-form-item>
          </el-col>
          <div :id="hidEditor" v-show="false" v-html="recordForm.record.ZK_INVESTOR.ZK_DESC"></div>
        </el-row>
      </el-form>
      <el-tabs value="first">
        <el-tab-pane label="机构团队" name="first">
          <el-table :data="recordForm.record.ZK_INVESTOR_TEAMS" stripe>
            <el-table-column sortable prop="ZK_AVATAR" label="头像">
              <template slot-scope="scope">
                <img class="column_logo" :src="scope.row.ZK_AVATAR" :alt="scope.row.ZK_NAME" />
              </template>
            </el-table-column>
            <el-table-column sortable prop="ZK_NAME" label="姓名" />
            <el-table-column sortable prop="ZK_POSITION" label="职位" />
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="投资案例" name="second">
          <el-table :data="recordForm.record.ZK_INVESTOR_CASES" stripe>
            <el-table-column sortable prop="ZK_TITLE" label="公司/项目" />
            <el-table-column sortable prop="ZK_INDUSTRY" label="行业" />
            <el-table-column sortable prop="ZK_MONEY" label="金额" />
            <el-table-column sortable prop="ZK_ROUNDS" label="轮次" />
            <el-table-column sortable prop="ZK_TIME" label="时间">
              <template slot-scope="scope">
                {{$common.ChangeDateFormat_hhmmss(scope.row.ZK_TIME, '-')}}
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button @click="recordForm.visible = false;">取 消</el-button>
        <el-button type="primary" @click="recordForm.flag ? null : updateRecord()">保 存</el-button>
        <el-button type="primary" @click="checkTarget()" v-if="recordForm.record.ZK_INVESTOR.ZK_ISSYNC!=='1'"><i class="el-icon-upload"></i> 同 步</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="'与目标数据库记录冲突（匹配到'+ targetForm.record.length +'条记录）'" :visible="targetForm.visible" width="70%" :show-close="false">
      <el-card v-for="item in targetForm.record" :key="item.ZK_INVESTOR.ZK_NAME" style="margin-bottom:20px;">
        <div slot="header" class="target_item_header">
          <img class="column_logo" :src="item.ZK_INVESTOR.ZK_LOGO" />
          <span>{{item.ZK_INVESTOR.ZK_TITLE}}</span>
          <el-button type="text" @click="showTargetDesc(item.ZK_INVESTOR)">查看简介</el-button>
        </div>
        <el-tabs value="first">
          <el-tab-pane label="机构团队" name="first">
            <el-table :data="item.ZK_INVESTOR_TEAMS" stripe>
              <el-table-column sortable prop="ZK_AVATAR" label="头像">
                <template slot-scope="scope">
                  <img class="column_logo" :src="scope.row.ZK_AVATAR" :alt="scope.row.ZK_NAME" />
                </template>
              </el-table-column>
              <el-table-column sortable prop="ZK_NAME" label="姓名" />
              <el-table-column sortable prop="ZK_POSITION" label="职位" />
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="投资案例" name="second">
            <el-table :data="item.ZK_INVESTOR_CASES" stripe>
              <el-table-column sortable prop="ZK_TITLE" label="公司/项目" />
              <el-table-column sortable prop="ZK_INDUSTRY" label="行业" />
              <el-table-column sortable prop="ZK_MONEY" label="金额" />
              <el-table-column sortable prop="ZK_ROUNDS" label="轮次" />
              <el-table-column sortable prop="ZK_TIME" label="时间">
                <template slot-scope="scope">
                  {{$common.ChangeDateFormat_hhmmss(scope.row.ZK_TIME, '-')}}
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="targetForm.visible = false;">关 闭</el-button>
        <el-button type="primary" disabled>合并冲突</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selection: [],
      records: [],
      tableParam: {
        keyword: '',
        _keyword: '',
        prop: '',
        order: '',
        pagesize: 25,
        pageno: 1,
        total: 0,
        loading: false,
        dropdown: [
          { key: 'ZK_TITLE', value: '机构' },
          { key: 'ZK_ISSYNC', value: '同步' },
        ],
        keycurrent: 0,
      },
      recordForm: {
        flag: true,
        record: {
          ZK_INVESTOR: {},
          ZK_INVESTOR_CASES: [],
          ZK_INVESTOR_TEAMS: [],
        },
        visible: false,
        index: -1,
      },
      recordformRules: {
        ZK_TITLE: [
          { required: true, message: '请输入机构名称', trigger: 'blur' },
        ],
        ZK_LOGO: [
          { required: true, message: '请输入LOGO地址', trigger: 'blur' },
        ],
      },
      hidEditor: `h_${this.$common.Guid()}`,
      targetForm: {
        record: [],
        visible: false,
      },
    };
  },
  created() {
    this._recordForm = JSON.stringify(this.recordForm);
    this.query();
  },
  methods: {
    query() {
      this.tableParam.loading = true;
      this.$http
        .get('/api/investor/list', {
          params: {
            KEYWORD: this.tableParam.keyword,
            TYPE: this.tableParam.dropdown[this.tableParam.keycurrent].key,
            PROP: this.tableParam.prop,
            ORDER: this.tableParam.order,
            PAGESIZE: this.tableParam.pagesize,
            PAGENO: this.tableParam.pageno,
          },
        })
        .then(res => {
          this.tableParam.loading = false;
          if (res.data.flag === 'True') {
            this.tableParam.total = Number.parseInt(res.data.message, 10);
            this.records = res.data.result;
          }
        });
    },
    updateKeyCurrent(command) {
      this.tableParam.dropdown.forEach((item, index) => {
        if (item.key === command) {
          this.tableParam.keycurrent = index;
        }
      });
    },
    selectionChange(sels) {
      const list = [];
      sels.forEach(item => {
        list.push(this.records[item]);
      });
      this.selection = list;
    },
    recordFormInit() {
      if (this.$refs.recordForm) {
        this.$refs.recordForm.resetFields();
      }
      this.recordForm = JSON.parse(this._recordForm);
    },
    currentChange(currentPage) {
      if (this.tableParam.pageno !== currentPage) {
        this.tableParam.pageno = currentPage;
        this.query();
      }
    },
    sortChange(s) {
      if (s.sortOrder) {
        this.tableParam.prop = s.sortProp;
        this.tableParam.order = s.sortOrder.includes('desc')
          ? 'descending'
          : 'ascending';
        this.tableParam.pageno = 1;
        this.query();
      }
    },
    delRecord(scope) {
      this.$confirm('是否删除该机构记录', '删除提示', { type: 'warning' })
        .then(() => {
          this.$http
            .post('/api/investor/delete', { IDS: scope.row.ZK_ID })
            .then(res => {
              if (res.data.flag === 'True') {
                this.records.splice(scope.index, 1);
                this.$notify({
                  title: '成功',
                  message: '已成功删除一条记录',
                  type: 'success',
                });
              }
            });
        })
        .catch(() => {});
    },
    batchDelete() {
      const ids = [];
      if (this.selection.length === 0) {
        this.$message.error('请先选中需要删除的选项');
        return;
      }
      this.selection.forEach(item => {
        ids.push(item.ZK_ID);
      });
      this.$confirm('是否删除选中的机构记录', '删除提示', { type: 'warning' })
        .then(() => {
          this.$http
            .post('/api/investor/delete', { IDS: ids.join(',') })
            .then(res => {
              if (res.data.flag === 'True') {
                this.$notify({
                  title: '成功',
                  message: '成功删除多条记录(一秒后将自动刷新页面)',
                  type: 'success',
                });
                setTimeout(() => {
                  window.location.reload();
                }, 500);
              }
            });
        })
        .catch(() => {});
    },
    updateContent(_content) {
      this.recordForm.record.ZK_INVESTOR.ZK_DESC = _content;
    },
    getRecord(scope) {
      this.$http
        .get('/api/investor/detail', { params: { UID: scope.row.ZK_ID } })
        .then(res => {
          if (res.data.flag === 'True') {
            this.recordForm.record = res.data.result;
            this.recordForm.flag = false;
            this.recordForm.visible = true;
            this.recordForm.index = scope.index;
          }
        });
    },
    checkTarget(uid) {
      const promise = new Promise((resolve, reject) => {
        this.$http
          .get('/api/investor/targetdetail', {
            params: {
              UID: uid || this.recordForm.record.ZK_INVESTOR.ZK_ID,
            },
          })
          .then(res => {
            if (res.data.flag === 'True') {
              if (typeof uid === 'undefined') {
                if (res.data.result.length === 0) {
                  this.$confirm(
                    '目标数据库暂无该机构信息，是否同步？',
                    '同步提示',
                    {
                      confirmButtonText: '立即同步',
                      cancelButtonText: '取消',
                      type: 'success',
                    },
                  )
                    .then(() => {
                      this.syncTarget();
                    })
                    .catch(() => {});
                } else {
                  this.recordForm.visible = false;
                  this.targetForm.record = res.data.result;
                  this.targetForm.visible = true;
                }
              }
            }
            resolve(res);
          })
          .catch(() => {
            reject();
          });
      });
      return promise;
    },
    showTargetDesc(scope) {
      this.$message({
        dangerouslyUseHTMLString: true,
        message: scope.ZK_DESC,
      });
    },
    updateRecord() {
      this.$refs.recordForm.validate(valid => {
        if (valid) {
          if (!this.recordForm.record.ZK_INVESTOR.ZK_DESC) {
            this.$message.warning('请填写机构详情');
            return;
          }
          this.$http
            .post('/api/investor/update', this.recordForm.record.ZK_INVESTOR)
            .then(res => {
              if (res.data.flag === 'True') {
                const form = JSON.parse(JSON.stringify(this.recordForm.record));
                this.records[this.recordForm.index].ZK_TITLE = form.ZK_INVESTOR.ZK_TITLE;
                this.records[this.recordForm.index].ZK_LOGO = form.ZK_INVESTOR.ZK_LOGO;
                this.records[this.recordForm.index].ZK_DESC = form.ZK_INVESTOR.ZK_DESC;
                this.$notify({
                  title: '成功',
                  message: '保存机构信息成功',
                  type: 'success',
                });
                this.recordFormInit();
              }
            });
        } else {
          this.$message.warning('请验证数据有效性');
        }
      });
    },
    syncTarget(uid) {
      const promise = new Promise((resolve, reject) => {
        this.$http
          .post('/api/investor/synctarget', {
            UID: uid || this.recordForm.record.ZK_INVESTOR.ZK_ID,
          })
          .then(res => {
            if (res.data.flag === 'True') {
              if (res.data.result > 0) {
                this.$notify({
                  title: '成功',
                  message: res.data.message,
                  type: 'success',
                });
                if (typeof uid === 'undefined') {
                  this.records[this.recordForm.index].ZK_ISSYNC = '1';
                  this.recordFormInit();
                }
              } else {
                this.$notify.info({
                  title: '提示',
                  message: res.data.message,
                });
              }
            }
            resolve(res);
          })
          .catch(() => {
            reject();
          });
      });
      return promise;
    },

    /**
     * 批量同步机构
     * promise调用checkTarget和syncTarget
     */
    batchSync() {
      if (this.selection.length === 0) {
        this.$message.error('请先选中需要同步的机构');
        return;
      }
      this.$confirm(
        '是否立即同步选中的机构(自动跳过有冲突的机构)',
        '同步提示',
        {
          type: 'warning',
        },
      )
        .then(() => {
          const tasks = [];
          this.selection.forEach(item => {
            tasks.push(
              new Promise(resolve => {
                if (item.ZK_ISSYNC === '1') {
                  setTimeout(() => {
                    this.$notify.info({
                      title: '提示',
                      message: `${item.ZK_TITLE}已同步，跳过处理`,
                    });
                  }, 250);
                  resolve();
                } else {
                  this.checkTarget(item.ZK_ID).then(res => {
                    if (res.data.flag === 'True') {
                      if (res.data.result.length > 0) {
                        this.$notify({
                          title: '冲突',
                          message: `匹配到${
                            res.data.result.length
                          }条冲突记录，跳过同步`,
                          type: 'warning',
                        });
                        resolve();
                      } else {
                        this.syncTarget(item.ZK_ID).then(() => {
                          resolve();
                        });
                      }
                    } else {
                      resolve();
                    }
                  });
                }
              }),
            );
          });
          Promise.all(tasks).then(() => {
            this.$notify({
              title: '成功',
              message: '结束批量同步操作(三秒后将自动刷新页面)',
              type: 'success',
            });
            setTimeout(() => {
              window.location.reload();
            }, 3400);
          });
        })
        .catch(() => {});
    },
  },
};
</script>

<style>
#Investor_vue .botton_toolbar {
  border: 1px solid #f2f2f2;
  box-shadow: 0 0 5px #f2f2f2;
  padding: 10px;
  margin: 10px 0 20px 0;
}
#Investor_vue .botton_toolbar:hover {
  background: #f2f2f2;
  box-shadow: none;
}
#Investor_vue .column_logo {
  width: 46px;
  height: auto;
  display: inherit;
  margin: 6px 0;
  border-radius: 4px;
}

#Investor_vue .target_item_header {
  display: flex;
  justify-content: center;
  align-items: center;
}

#Investor_vue .target_item_header > img {
  flex: none;
}

#Investor_vue .target_item_header > span {
  flex: 1;
  font-size: 16px;
  font-weight: bold;
  padding: 0 10px;
}

#Investor_vue .target_item_header .el-button {
  flex: none;
}
</style>
